package com.shuyun.stockdata;

import com.alibaba.fastjson.JSON;
import com.shuyun.stockdata.constant.Constant;
import com.shuyun.stockdata.pojo.Data;
import com.shuyun.stockdata.pojo.TimesHttp;
import com.shuyun.stockdata.utils.DateUtil;
import com.shuyun.stockdata.utils.HandleFilleUtil;
import com.shuyun.stockdata.utils.HttpClientUtil;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Created by sw on 2018/3/15
 */
public class StockDataToFile {

    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("请输入参数");
            System.exit(0);
        }
        System.out.println("您输入参数是:" + args[0]);


        String date = DateUtil.getStringDateShort();
        //股票代码列表
        List<String> lst = Arrays.asList(HandleFilleUtil.readValue(Constant.FILE_PATH, Constant.KEY).split(","));

        lst.stream().forEach(stockCode -> {
            System.out.println("正在获取股票代码为：" + stockCode + "的数据");
            String result = HttpClientUtil.doGet("https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=" + stockCode + "&outputsize=full&apikey=7WB1UUKGC1EG46BL");
            //System.out.println(result);

            Data data = JSON.parseObject(result, Data.class);
            Map<String, TimesHttp> timesHttpMap = data.getTimeSeries();

            if ("init".equals(args[0])) {
                //遍历map
                //获取全部数据
                timesHttpMap.forEach((timestamp, timesHttp) -> {
                    try {
                        HandleFilleUtil.writeData(HandleFilleUtil.getDataAll(timestamp, timesHttp, data), HandleFilleUtil.readValue(Constant.FILE_PATH, Constant.PATH_KEY) + date + ".txt");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });

            } else {
                //根据给定的日期获取数据
                Arrays.asList(args).stream().forEach(dateSrc -> {

                    try {
                        HandleFilleUtil.writeData(HandleFilleUtil.getDataByDate(timesHttpMap, data.getMetaData().getSymbol(), args[0]), HandleFilleUtil.readValue(Constant.FILE_PATH, Constant.PATH_KEY) + dateSrc + ".txt");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                });
            }
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }
}
